import os
from pathlib import Path
import shutil
import time
from datetime import datetime

import schedule

LOG_FILE = "pyCacheCleaner.log"
SAVE_FOLDER = "E:\\Game\\Steamcmd\\steamapps\\common\\PalServer\\Pal"
TIMER = "04:05:00"  # 每天04:05执行一次

def cleaner():
    pass


def remove_files():
    save_name = "Saved-" + datetime.now().strftime("%y%m%d") + "_040000"
    save_inner_path1 = "Crashes"
    save_inner_path2 = "SaveGames\\0\\B290E4494D62B09EB5B2089DE57DCF38\\backup"
    save_data = os.path.join(SAVE_FOLDER, save_name)
    path1 = os.path.join(save_data, save_inner_path1)
    path2 = os.path.join(save_data, save_inner_path2)
    if os.path.exists(path1):
        shutil.rmtree(path1)
        mylog(f"已删除[{save_name}]Crashes")
    else:
        mylog(f"{path1}不存在")
    if os.path.exists(path2):
        shutil.rmtree(path2)
        mylog(f"已删除[{save_name}]Backup")
    else:
        mylog(f"{path2}不存在")
    mylog(f"cleaned")


def mylog(s: str = ""):
    s = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]" + s
    print(s)
    with open(LOG_FILE, "a", encoding="utf-8") as f:
        f.write(s + "\n")
        f.close()


if __name__ == "__main__":
    os.system("title pyCacheCleaner")
    if not os.path.exists(LOG_FILE):
        Path(LOG_FILE).touch()
    schedule.run_pending()
    schedule.every().day.at(TIMER).do(remove_files)
    mylog(f"[Init] Program will clean {SAVE_FOLDER} at {TIMER} everyday")
    while True:
        schedule.run_pending()
        time.sleep(1)
